package hips.tools;

@SuppressWarnings("unused")
public class Neighborhood{
    public final static int NEIGHBORS = 4;
    public final static int LEFT = 1;
    public final static int RIGHT = 2;
    public final static int UP = 3;
    public final static int DOWN = 4;

    private int n;
	private int height;
	private int width;
	private Iterator iterator;
	
    public Neighborhood(int width, int height){
        this.n = height * width;
        this.height = height;
        this.width = width;
        iterator = new Iterator();
    }

    public class Iterator{
    	private int pos;
    	private int cell;
    	private int neighbor;
    	
    	Iterator(int cell){
    		clearIterator(cell);
    	}
    	
    	Iterator(){}
    	
    	public Iterator clearIterator(int cell){
    		this.cell = cell;
    		pos = 0;
    		neighbor = -1;
    		return this;
    	}
    	
    	public boolean hasNext(){
    		do{
    			if (pos == NEIGHBORS){
    				return false;
    			}
    			neighbor = getNeighbor(cell, ++pos);
    		}while(neighbor == -1);
    		return true;
    	}
    	
    	public int get(){
    		return neighbor;
    	}
    }
    
    public Iterator iterator(int cell){
    	return iterator.clearIterator(cell);
    }
    
    public Iterator newIterator(int cell){
    	return new Iterator(cell);
    }
    
    public int getNeighbor(int cell, int pos){
          switch (pos){
               case 1:{
                    if (cell % width > 0)
                         return cell - 1;
                    else
                         return -1;
               }
               case 2:{
                    if (cell % width < width - 1)
                         return cell + 1;
                    else
                         return -1;
               }
               case 3:{
                    if (cell >= width)
                         return cell - width;
                    else
                         return -1;
               }
               case 4:{
                    if (cell + width  < n)
                         return cell + width;
                    else
                         return -1;
               }
          }
          return -1;
     }
}
